package com.zs.myorm.framework.core.session;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.zs.myorm.framework.core.aop.MyInvocationHandlerMapper;
import com.zs.myorm.framework.core.execute.ISqlExecute;
import com.zs.myorm.framework.core.method.IMethodHandler;
import com.zs.myorm.framework.core.method.IMethodHandlerStrategyContext;
import com.zs.myorm.framework.core.method.impl.FindAllMethodHandlerImpl;
import com.zs.myorm.framework.core.method.impl.MethodHandlerStrategyContextImpl;
import com.zs.myorm.framework.core.method.impl.RemoveMethodHandlerImpl;
import com.zs.myorm.framework.core.method.impl.SaveMethodHandlerImpl;

public abstract class abstractSqlSession implements ISqlSession {

	private ISqlExecute sqlExecute;

	private Map<Class<?>, Object> mappers = new java.util.concurrent.ConcurrentHashMap<Class<?>, Object>();

	public <T> T getMapper(Class<T> clase) {
		Object mapper = mappers.get(clase);
		if (mapper == null) {
			mapper = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { clase }, getInvocationHandler());
			mappers.put(clase, mapper);
		}
		return (T) mapper;
	}

	public ISqlExecute getSqlExecute() {
		return sqlExecute;
	}

	public void setSqlExecute(ISqlExecute sqlExecute) {
		this.sqlExecute = sqlExecute;
	}

	InvocationHandler getInvocationHandler() {
		MyInvocationHandlerMapper handler = new MyInvocationHandlerMapper();
		handler.setContext(getMethodHandlerStrategyContext());
		return handler;
	}

	IMethodHandlerStrategyContext getMethodHandlerStrategyContext() {
		MethodHandlerStrategyContextImpl context = new MethodHandlerStrategyContextImpl();
		context.setSqlExecute(sqlExecute);
		context.setMethodHandlers(getMethodHandlers());
		return context;
	}

	private List<IMethodHandler> getMethodHandlers() {
		List<IMethodHandler> list = new ArrayList<IMethodHandler>();
		list.add(new FindAllMethodHandlerImpl());
		list.add(new SaveMethodHandlerImpl());
		list.add(new RemoveMethodHandlerImpl());
		return list;
	}
}
